const UsersModels = require('../models/UsersModel')
const BaseController = require('./BaseController')
const createToken = require('../token/createToken')
const day = require('dayjs')

class UsersController extends BaseController {
  constructor(args) {
    super(args)
  }

  /**用户列表*/
  static async list(ctx) {
    let res
    try {
      res = await UsersModels.find()
      ctx.success(res)
    } catch (e) {
      ctx.fail(e.message)
    }
  }

  /**查询用户详情*/
  static async detail(ctx) {
    console.log('ctx.request.body', ctx.query)
    try {
      const res = await UsersModels.findOne({
        _id: ctx.query._id
      })
      ctx.success(res)
    } catch (e) {
      ctx.fail(e.message)
    }
  }

  /**更新用户信息*/
  static async update(ctx) {
    try {
      const res = await UsersModels.updateOne(
        {
          _id: ctx.request.body._id
        },
        {
          user_name: ctx.request.body.user_name,
          phone_num: ctx.request.body.phone_num,
          age: ctx.request.body.age,
          update_time: day().format('YYYY-MM-DD HH:mm:ss')
        }
      )
      ctx.success(res)
    } catch (e) {
      ctx.fail(e.message)
    }
  }

  /**删除用户*/
  static async delete(ctx) {
    try {
      const res = await UsersModels.remove({
        _id: ctx.request.body._id
      })
      ctx.success(res)
    } catch (e) {
      ctx.fail(e.message)
    }
  }

  /**注册/添加用户*/
  static async add(ctx) {
    const phone_num = ctx.request.body.phone_num
    const password = ctx.request.body.password
    const user_name = ctx.request.body.user_name
    try {
      const doc = await UsersModels.findOne({ phone_num })
      if (doc) {
        return ctx.fail('用户名已经存在')
      }
      const res = await UsersModels.create({
        phone_num,
        password,
        token: createToken(phone_num),
        user_name,
        age: 0, // 默认年龄为0
        create_time: day().format('YYYY-MM-DD HH:mm:ss')
      })
      ctx.success(res)
    } catch (e) {
      ctx.fail(e.message)
    }
  }

  /**登录*/
  static async login(ctx) {
    const phone_num = ctx.request.body.phone_num
    const password = ctx.request.body.password

    try {
      const doc = await UsersModels.findOne({ phone_num })
      if (!doc) {
        return ctx.fail('检查到用户名不存在')
      }
      if (doc.password === password) {
        console.log('密码一致!')

        //生成一个新的token,并存到数据库
        const token = createToken(phone_num)
        console.log('生成一个新的token,并存到数据库--->', token)
        doc.token = token
        ctx.success({
          user_id: doc._id,
          phone_num: doc.phone_num,
          user_name: doc.user_name,
          age: doc.age,
          token: doc.token
        })
      } else {
        ctx.fail('密码错误!')
      }
    } catch (e) {
      ctx.fail(e.message)
    }
  }
}
module.exports = UsersController
